//
//  YLArrayExtension.swift
//  iosh5vue
//
//  Created by lyl on 2021/3/1.
//  Copyright © 2021 lyl. All rights reserved.
//

import Foundation
extension Array {
    func toJSONString() -> String? {
        if !JSONSerialization.isValidJSONObject(self) {
            print("dict转json失败")
            return nil
        }
        if let newData: Data = try? JSONSerialization.data(withJSONObject: self, options: []) {
            guard let JSONString = String(data: newData, encoding: .utf8)?.replacingOccurrences(of: "\\/", with: "/") else {
                return ""
            }
            return JSONString
        }
        print("dict转json失败")
        return nil
    }
    static func initt<T:Decodable>(string jsonString:String,_ type:[T].Type) throws -> Array<T> {
        guard let jsonData = jsonString.data(using: .utf8) else {
            print(MapError.jsonToDataFail)
            throw MapError.jsonToDataFail
        }
        let decoder = JSONDecoder()
//        if let obj = try? decoder.decode(type, from: JSonData) {
//            return obj
//        }
//        print(MapError.jsonToArrFail)
//        throw MapError.jsonToArrFail
        
        #if DEBUG
        
        return try! decoder.decode(type, from: jsonData)
        
        #else
        
        if let obj = try? decoder.decode(type, from: jsonData) {
            return obj
        }
        print(MapError.jsonToModelFail)
        throw MapError.jsonToModelFail
        
        #endif
        //        return try! decoder.decode(type, from: jsonData)
    }
}
